package com.lakeworks.framework.web.exception;

import com.lakeworks.common.constant.HttpStatus;
import com.lakeworks.common.core.domain.AjaxResult;
import com.lakeworks.common.enums.ChannelErrorEnum;
import com.lakeworks.common.exception.DemoModeException;
import com.lakeworks.common.exception.ServiceException;
import com.lakeworks.common.exception.base.channel.ThirdChannelException;
import com.lakeworks.common.exception.response.ResponseException;
import com.lakeworks.common.utils.SecurityUtils;
import com.lakeworks.common.utils.ServletUtils;
import com.lakeworks.common.utils.StringUtils;
import com.lakeworks.domain.SysChannelAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.io.IOException;

import static com.lakeworks.common.core.domain.AjaxResult.error;

/**
 * 全局异常处理器
 *
 * @author lakeworks
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Object handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        log.error("请求方式：[{}]，请求地址：[{}],权限校验失败：[{}]", request.getMethod(), request.getRequestURI(), e.getMessage());
        if (isSysChannelAuth())
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        return error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request) {
        log.error("请求地址：[{}],不支持[{}]请求", request.getRequestURI(), e.getMethod());
        return error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error("请求方式：[{}]，请求地址：[{}],业务异常：[{}]", request.getMethod(), request.getRequestURI(), e.getMessage(), e);
        Integer code = e.getCode();
        return StringUtils.isNotNull(code) ? error(code, e.getMessage()) : error(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Object handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("请求方式：[{}]，请求地址：[{}]，运行时异常", request.getMethod(), request.getRequestURI(), e);
        if (isSysChannelAuth())
            return ResponseEntity.status(HttpStatus.ERROR).build();
        return error("系统异常，请联系管理员");
    }

    @ExceptionHandler(ResponseException.class)
    public Object handleResponseException(ResponseException e, HttpServletRequest request) {
        log.error("请求方式：[{}]，请求地址：[{}]，Response异常", request.getMethod(), request.getRequestURI(), e);
        if (isSysChannelAuth())
            return ResponseEntity.status(HttpStatus.ERROR).build();
        return error(e.getMessage());
    }

    @ExceptionHandler(ThirdChannelException.class)
    public ResponseEntity handleChannelException(ThirdChannelException e, HttpServletRequest request) throws IOException {
        log.error("请求方式：[{}]，请求地址：[{}]，ChannelException: [{}]",request.getMethod(),request.getRequestURI(),ChannelErrorEnum.message(e.getMessage()),e);
        return ResponseEntity.badRequest().body(ChannelErrorEnum.byCode(e.getMessage()));
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e, HttpServletRequest request) {
        log.error("请求方式：[{}]，请求地址：[{}]，发生系统异常", request.getMethod(), request.getRequestURI(), e);
        if (isSysChannelAuth())
            return ResponseEntity.status(HttpStatus.ERROR).build();
        return error("系统异常，请联系管理员");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(BindException e) {
        log.error("请求方式：[{}]，请求地址：[{}],自定义验证异常：[{}]", ServletUtils.getRequest().getRequestURI(), e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        if (isSysChannelAuth()) {
            log.error("请求方式：[{}]，请求地址：[{}]，自定义验证异常：[{}]", ServletUtils.getRequest().getMethod(), ServletUtils.getRequest().getRequestURI(), ChannelErrorEnum.message(message), e);
            return ResponseEntity.badRequest().body(ChannelErrorEnum.byCode(message));
        }
        log.error(e.getMessage(), e);
        return error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Object handleConstraintViolationExceptionException(ConstraintViolationException e) {
        int index = e.getMessage().indexOf(" ");
        String message = e.getMessage().substring(index);

        if (isSysChannelAuth()) {
            log.error("请求方式：[{}]，请求地址：[{}]，自定义验证异常：[{}]", ServletUtils.getRequest().getMethod(), ServletUtils.getRequest().getRequestURI(), ChannelErrorEnum.message(message), e);
            return ResponseEntity.badRequest().body(ChannelErrorEnum.byCode(message));
        }
        log.error(e.getMessage(), e);
        return error(message);
    }


    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public AjaxResult handleDemoModeException(DemoModeException e) {
        return error("演示模式，不允许操作");
    }

    private Boolean isSysChannelAuth() {
        return SecurityUtils.getPrincipal() instanceof SysChannelAuth;
    }

}
